package com.lcq.privacysupport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PrivacyDialog extends AlertDialog {
    private final Activity activity;
    private final PrivacyCallback callback;
    private final ProtocolResult protocolResult;

    private PrivacyDialog(Builder builder) {
        super(builder.activity);
        activity = builder.activity;
        protocolResult = builder.result;
        callback = builder.callback;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_privacy);
        setCancelable(false);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Button refuseBt = findViewById(R.id.refuse);
        Button agreeBtn = findViewById(R.id.agree);


        refuseBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用户拒绝则关闭弹窗、关闭应用，你也可以弹出挽留的对话框，让用户继续选择是否退出
                dismiss();
                activity.finish();
                //Process.killProcess(Process.myPid());
                //System.exit(0);
            }
        });

        agreeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用户同意则保存同意状态，下次启动检测这个状态不再弹隐私协议弹窗,并回调onAgree
                dismiss();
                activity.getSharedPreferences(Privacy.SP_PRIVACY, Context.MODE_PRIVATE).edit()
                        .putBoolean(Privacy.PRIVACY_AGREE, true)
                        .apply();
                if (callback != null) {
                    callback.onAgree();
                }
            }
        });

        initContentTv();
    }

    /**
     * 对弹窗里面的类容进行初始化，
     */
    private void initContentTv() {
        TextView contentTv = findViewById(R.id.content);
        //将内容进行Html格式化后的CharSequence设置给TextView,并用来初始化SpannableString
        CharSequence htmlText = Html.fromHtml(protocolResult.getContent());
        contentTv.setText(htmlText);
        SpannableString spannableString = new SpannableString(htmlText);
        for (final ProtocolInfo p : protocolResult.getProtocolList()) {
            setClickableSpan(spannableString, p);
        }

        contentTv.setMovementMethod(LinkMovementMethod.getInstance()); //点击事件才能起效
        contentTv.setHighlightColor(Color.TRANSPARENT);
        contentTv.setText(spannableString);
    }

    /**
     * 设置点击文字的点击事件
     *
     * @param spannableString
     * @param protocolInfo
     */
    private void setClickableSpan(SpannableString spannableString, final ProtocolInfo protocolInfo) {
        String clickText = "《" + protocolInfo.getName() + "》";//被点击文字
        String content = spannableString.toString();
        int index = content.indexOf(clickText);//获取可点击文字的首次出现位置
        while (index > 0) {//循环设置可点击文字的ClickableSpan，并处理点击事件
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Toast.makeText(activity, "点击了" + clickText + ",跳转到" + protocolInfo.getType(), Toast.LENGTH_SHORT).show();

                    //模拟通过type请求服务器协议接口返回的结果，并将结果中的content和name传递给AgreementActivity
                    ProtocolResult result = ProtocolResult.obtain(protocolInfo.getType());
                    Intent intent = new Intent(activity, ProtocolActivity.class);
                    intent.putExtra(ProtocolActivity.EXTRA_CONTENT, result.getContent());
                    intent.putExtra(ProtocolActivity.EXTRA_TITLE, result.getName());
                    activity.startActivity(intent);
                }
            }, index, index + clickText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            //获取下一个可点击文字的位置
            index = content.indexOf(clickText, index + clickText.length());
        }
    }

    @Override
    public void show() {
        super.show();
        //横竖屏设置Dialog的不同的宽高比
        Window window = this.getWindow();
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams params = window.getAttributes();
        if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            params.width = (int) (display.getWidth() * 0.8);
            params.height = (int) (display.getHeight() * 0.6);
        } else {
            params.width = (int) (display.getHeight() * 0.8);
            params.height = (int) (display.getHeight() * 0.9);
        }

        window.setAttributes(params);
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    public static final class Builder {
        private Activity activity;
        private PrivacyCallback callback;
        private ProtocolResult result;

        public Builder() {
        }

        public Builder activity(Activity val) {
            activity = val;
            return this;
        }

        public Builder callback(PrivacyCallback val) {
            callback = val;
            return this;
        }

        public Builder protocolResult(ProtocolResult val) {
            result = val;
            return this;
        }

        public PrivacyDialog build() {
            return new PrivacyDialog(this);
        }
    }
}
